package com.xinqi.modules.mq.rongyun.third.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.esotericsoftware.minlog.Log;
import com.xinqi.common.core.constant.CacheConstants;
import com.xinqi.common.core.constant.ConfigKeyConstants;
import com.xinqi.common.redis.utils.RedisUtils;
import com.xinqi.modules.chat.chat.group.message.GroupNoticeMessage;
import com.xinqi.modules.chat.chat.official.dto.rsp.ChatAssistantContentMessageResultDTO;
import com.xinqi.modules.chat.chat.official.json.ChatRemindMessage;
import com.xinqi.modules.mq.rongyun.third.message.CustomTypeMessage;
import com.xinqi.modules.mq.rongyun.third.service.RongyunService;
import io.rong.RongCloud;
import io.rong.messages.CustomTxtMessage;
import io.rong.methods.chatroom.ban.Ban;
import io.rong.methods.chatroom.ban.BanAllMemberWhitelist;
import io.rong.methods.conversation.Conversation;
import io.rong.methods.group.Group;
import io.rong.methods.group.gag.Gag;
import io.rong.methods.message._private.Private;
import io.rong.methods.message.chatroom.Chatroom;
import io.rong.methods.message.system.MsgSystem;
import io.rong.methods.user.User;
import io.rong.methods.user.blacklist.Blacklist;
import io.rong.methods.user.block.Block;
import io.rong.models.Result;
import io.rong.models.chatroom.ChatroomMember;
import io.rong.models.chatroom.ChatroomModel;
import io.rong.models.conversation.ConversationModel;
import io.rong.models.group.GroupMember;
import io.rong.models.group.GroupModel;
import io.rong.models.message.ChatroomMessage;
import io.rong.models.message.GroupStatusMessage;
import io.rong.models.message.PrivateMessage;
import io.rong.models.message.SystemMessage;
import io.rong.models.response.ResponseResult;
import io.rong.models.response.TokenResult;
import io.rong.models.user.BanModel;
import io.rong.models.user.UserModel;
import io.rong.util.CodeUtil;
import io.rong.util.HttpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Log4j2
@Service
public class RongyunServiceImpl implements RongyunService {

    @Value("${third.chat.rongyun.key}")
    private String rongYunKey;
    @Value("${third.chat.rongyun.secret}")
    private String rongYunSecret;

    /* 用户注册融云 */
    @Override
    public String registUser(String userId, String userName, String avatar) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        User User = rongCloud.user;
        //获取系统默认头像
        String defaultAvatar = RedisUtils.getCacheMapValue(CacheConstants.SYS_CONFIG_HASH_KEY, ConfigKeyConstants.SYS_DEFAULT_AVATAR);
        UserModel user = new UserModel().setId(userId).setName(userName).setPortrait(avatar == null ? defaultAvatar : avatar);
        try {
            TokenResult r = User.register(user);
            return r.getToken();
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    /* 刷新用户信息 */
    public boolean updateUser(String userId, String userName, String avatar) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        User User = rongCloud.user;
        //获取系统默认头像
        String defaultAvatar = RedisUtils.getCacheMapValue(CacheConstants.SYS_CONFIG_HASH_KEY, ConfigKeyConstants.SYS_DEFAULT_AVATAR);
        UserModel user = new UserModel().setId(userId).setName(userName).setPortrait(avatar == null ? defaultAvatar : avatar);
        try {
            Result result = User.update(user);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云创建群组 */
    public boolean creatGroup(String groupId, String groupName, String userId) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Group Group = rongCloud.group;
        GroupMember[] members = {new GroupMember().setId(userId)};
        GroupModel group = new GroupModel().setId(groupId).setName(groupName).setMembers(members);
        try {
            Result result = (Result) Group.create(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    /* 融云加入群组 */
    public boolean joinGroup(String groupId, String groupName, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Group Group = rongCloud.group;
        GroupMember[] members = new GroupMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new GroupMember().setId(userIds[i]);
        }
        GroupModel group = new GroupModel()
            .setId(groupId)
            .setMembers(members)
            .setName(groupName);
        try {
            Result result = (Result) Group.join(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云更新群名称 */
    public boolean updateGroup(String groupId, String groupName) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Group Group = rongCloud.group;
        GroupModel group = new GroupModel()
            .setId(groupId)
            .setName(groupName);
        try {
            Result result = Group.update(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云退出群组 */
    public boolean quitGroup(String groupId, String groupName, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Group Group = rongCloud.group;
        GroupMember[] members = new GroupMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new GroupMember().setId(userIds[i]);
        }
        GroupModel group = new GroupModel()
            .setId(groupId)
            .setMembers(members)
            .setName(groupName);
        try {
            Result result = (Result) Group.quit(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云解散群组 */
    public boolean dissGroup(String groupId, String userId) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Group Group = rongCloud.group;
        GroupModel group = new GroupModel().setId(groupId).setFromUserId(userId);
        GroupMember[] member = new GroupMember[]{new GroupMember().setId(userId)};
        group.setMembers(member);
        try {
            Result result = (Result) Group.dismiss(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 同步融云会话置顶
     * <p>
     * 请求示例
     * POST /conversation/top/set.json HTTP/1.1
     * Host: api-cn.ronghub.com
     * App-Key: uwd1c0sxdlx2
     * Nonce: 14314
     * Timestamp: 1408710653491
     * Signature: 45beb7cc7307889a8e711219a47b7cf6a5b000e8
     * Content-Type: application/x-www-form-urlencoded
     * <p>
     * userId=XivuFwkcl&targetId=RfqHbcjes&conversationType=1&setTop=true
     * 返回结果示例
     * HTTP/1.1 200 OK
     * Content-Type: application/json; charset=utf-8
     * <p>
     * {"code":200}
     * <p>
     * 参考于融云官方网站 https://doc.rongcloud.cn/imserver/server/v1/conversation/top
     *
     * @param userId           用户 ID，会话所属的用户
     * @param conversationType 会话类型。支持的会话类型包括：1（二人会话）、3（群组会话）、6（系统会话）
     * @param targetId         需要设置的目标 ID，根据会话类型不同为单聊用户 ID、群聊 ID、系统目标 ID
     * @param isTop            true 表示置顶，false 表示取消置顶
     * @return Boolean
     */
    @Override
    public boolean conversationTop(String userId, String conversationType, String targetId, boolean isTop) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("&userId=").append(URLEncoder.encode(userId, "UTF-8"));
            sb.append("&targetId=").append(URLEncoder.encode(targetId, "UTF-8"));
            sb.append("&conversationType=").append(URLEncoder.encode(conversationType, "UTF-8"));
            sb.append("&setTop=").append(isTop);

            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1);
            }
            HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(rongCloud.getConfig(), rongYunKey, rongYunSecret, "/conversation/top/set.json", "application/x-www-form-urlencoded");
            HttpUtil.setBodyParameter(body, conn, rongCloud.getConfig());
            String result = HttpUtil.returnResult(conn, rongCloud.getConfig());
            JSONObject json = JSONObject.parseObject(result);
            return Objects.equals("200", json.getString("code"));
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    //消息免打扰
    public boolean conversationDisturb(String userId, String targetId, CodeUtil.ConversationType type, Integer flag) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Conversation Conversation = rongCloud.conversation;
        ConversationModel conversation = new ConversationModel()
            .setType(type.getName())
            .setUserId(userId)
            .setTargetId(targetId);
        try {
            ResponseResult result = null;
            if (flag == 1) {
                result = Conversation.mute(conversation);
            } else {
                result = Conversation.unMute(conversation);
            }
            if (result.code == 200) {
                return true;
            } else {
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云发送单聊消息 */
    public boolean sentPrivateMsg(String senderId, String[] targetIds, String json) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Private Private = rongCloud.message.msgPrivate;
        CustomTxtMessage message = new CustomTxtMessage(json);
        PrivateMessage privateMessage = new PrivateMessage()
            .setSenderId(senderId)
            .setTargetId(targetIds)
            .setObjectName("xqkt:chat")
            .setContent(message)
            .setIsPersisted(0)
            .setMsgRandom(System.currentTimeMillis())
            .setContentAvailable(0);
        try {
            ResponseResult result = Private.send(privateMessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云发送聊天室消息 */
    public boolean sentRoomMsg(String senderId, String[] roomIds, String json) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Chatroom Chatroom = rongCloud.message.chatroom;
        CustomTxtMessage message = new CustomTxtMessage(json);
        ChatroomMessage roommessage = new ChatroomMessage()
            .setSenderId(senderId)
            .setTargetId(roomIds)
            .setObjectName("xqkt:chat")
            .setContent(message)
            .setIsPersisted(0)
            .setMsgRandom(System.currentTimeMillis());
        try {
            ResponseResult result = Chatroom.send(roommessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 发送融云系统通知
     *
     * @param targetIds
     * @param json
     * @return
     */
    @Override
    public boolean sentSystemCmdMsg(String[] targetIds, String json) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        MsgSystem system = rongCloud.message.system;
        CustomTxtMessage message = new CustomTxtMessage(json);
        SystemMessage sysmessage = new SystemMessage()
            .setSenderId("system")
            .setTargetId(targetIds)
            .setObjectName("xqkt:chat")
            .setContent(message)
            .setIsPersisted(0)
            .setMsgRandom(System.currentTimeMillis())
            .setContentAvailable(0);
        try {
            ResponseResult result = system.send(sysmessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean sentSystemCmdMsg(String senderId, String[] targetIds, String json) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        MsgSystem system = rongCloud.message.system;
        CustomTxtMessage message = new CustomTxtMessage(json);
        SystemMessage sysmessage = new SystemMessage()
            .setSenderId(senderId)
            .setTargetId(targetIds)
            .setObjectName("xqkt:chat")
            .setContent(message)
            .setIsPersisted(0)
            .setMsgRandom(System.currentTimeMillis())
            .setContentAvailable(0);
        try {
            ResponseResult result = system.send(sysmessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                log.error("融云系统通知发送失败 => send - {}," +
                    "\n result - {}", json, result);
                return false;
            }
        } catch (Exception e) {
            log.error("融云系统通知发送失败 => send - {}", json);
            return false;
        }
    }

    /**
     * 机器人 -- 新奇提醒消息发送
     *
     * @Title:
     * @MethodName: sentOfficialMsg
     * [senderId, objectName, targetIds, message]
     * @Return boolean
     * @Exception
     * @Description:
     * @author: yyzhen
     * @date: 2023/5/8 15:57
     */
    @Override
    public boolean sentRemindMsg(String senderId, String objectName, String[] targetIds, ChatRemindMessage message) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Private msgPrivate = rongCloud.message.msgPrivate;
        PrivateMessage privateMessage = new PrivateMessage()
            //新奇提醒机器人 userID
            .setSenderId(senderId)
            .setTargetId(targetIds)
            .setObjectName(objectName)
            .setContent(message)
            .setIsPersisted(1)
            .setMsgRandom(System.currentTimeMillis())
            //添加推送
            .setPushContent(message.getPushContent());
        try {
            ResponseResult result = msgPrivate.send(privateMessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                log.error("新奇提醒 => 融云消息发送失败 => send - {}," +
                    "\n result - {}", message, result);
                return false;
            }
        } catch (Exception e) {
            log.error("新奇提醒 => 融云消息发送失败 => send - {}", message);
            return false;
        }
    }

    /**
     * 发送群组通知类消息
     * <p>
     * 群组内小黑条消息
     * 加入群聊、退出群聊、修改群名称
     *
     * @param senderId
     * @param objectName
     * @param groupIds
     * @param message
     * @return
     */
    @Override
    public boolean sentGroupMsg(String senderId, String objectName, String[] groupIds, GroupNoticeMessage message) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        io.rong.methods.message.group.Group group = rongCloud.message.group;
        GroupStatusMessage groupMessage = new GroupStatusMessage()
            .setSenderId(senderId)
            .setGroupId(groupIds)
            .setObjectName(objectName)
            .setContent(message)
            .setIsIncludeSender(1)
            .setVerifyBlacklist(0)
            .setMsgRandom(System.currentTimeMillis());
        try {
            ResponseResult result = group.sendStatusMessage(groupMessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                log.error("群组通知 => 融云消息发送失败 => send - {}," +
                    "\n result - {}", message, result);
                return false;
            }
        } catch (Exception e) {
            log.error("群组通知 => 融云消息发送失败 => send - {}", message);
            return false;
        }
    }

    /**
     * 新奇助手、新奇提醒消息发送可更新消息内容
     *
     * @param senderId
     * @param objectName
     * @param targetIds
     * @param json
     * @return
     */
    @Override
    public boolean sentOfficialExtMsg(String senderId, String objectName, String[] targetIds, String json, String pushContent) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Private msgPrivate = rongCloud.message.msgPrivate;
        CustomTypeMessage message = new CustomTypeMessage(json, objectName);
        PrivateMessage privateMessage = new PrivateMessage()
            //新奇提醒机器人 userID
            .setSenderId(senderId)
            .setTargetId(targetIds)
            .setObjectName(objectName)
            .setContent(message)
            .setIsPersisted(1)
            .setMsgRandom(System.currentTimeMillis())
            .setExpansion(true);
        // 推送内容为空 则不添加推送
        if (Objects.nonNull(pushContent)) {
            privateMessage.setPushContent(pushContent);
        }
        try {
            ResponseResult result = msgPrivate.send(privateMessage);
            if (result.getCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 新奇助手、新奇提醒消息发送已更新消息内容
     *
     * @param senderId
     * @param objectName
     * @param targetIds
     * @param message
     * @return
     */
    @Override
    public Boolean sentUpdateOfficialExtMsg(String senderId, String objectName, String[] targetIds, ChatAssistantContentMessageResultDTO message) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("&msgUID=").append(URLEncoder.encode(message.getMsgUid(), "UTF-8"));
            sb.append("&userId=").append(URLEncoder.encode(senderId, "UTF-8"));
            sb.append("&conversationType=").append(URLEncoder.encode("1", "UTF-8"));
            sb.append("&targetId=").append(URLEncoder.encode(targetIds[0], "UTF-8"));
            Map<String, String> map = new HashMap<>();
            map.put("data", JSON.toJSONString(message));
            JSONObject jsonMessage = new JSONObject(map);
            sb.append("&extraKeyVal=").append(jsonMessage);
            sb.append("&isSyncSender").append(URLEncoder.encode("1", "UTF-8"));

            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1);
            }

            RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
            HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(rongCloud.getConfig(), rongYunKey, rongYunSecret, "/message/expansion/set.json", "application/x-www-form-urlencoded");
            HttpUtil.setBodyParameter(body, conn, rongCloud.getConfig());
            String result = HttpUtil.returnResult(conn, rongCloud.getConfig());
            JSONObject json = JSONObject.parseObject(result);
            return Objects.equals("200", json.getString("code"));
        } catch (Exception e) {
            Log.error(e.toString());
            return false;
        }
    }

    @Override
    /* 管理黑名单 */
    public boolean blackManager(String userId, String friendId, Integer status) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Blacklist BlackList = rongCloud.user.blackList;
        UserModel blackUser = new UserModel().setId(friendId);
        UserModel[] blacklist = {blackUser};
        UserModel user = new UserModel().setId(userId).setBlacklist(blacklist);
        try {
            Result resule = null;
            if (status == 2) {
                resule = (Result) BlackList.add(user);
            } else {
                resule = (Result) BlackList.remove(user);
            }
            if (resule != null && resule.getCode() == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云群禁言 */
    public boolean groupTaboo(String groupId, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Gag Gag = rongCloud.group.gag;
        GroupMember[] members = new GroupMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new GroupMember().setId(userIds[i]);
        }
        GroupModel group = new GroupModel()
            .setId(groupId)
            .setMembers(members)
            .setMinute(0);
        try {
            Result result = Gag.add(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 融云解除群禁言 */
    public boolean groupTabooClose(String groupId, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Gag Gag = rongCloud.group.gag;
        GroupMember[] members = new GroupMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new GroupMember().setId(userIds[i]);
        }
        GroupModel group = new GroupModel()
            .setId(groupId)
            .setMembers(members)
            .setMinute(5);
        try {
            Result result = Gag.remove(group);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /* 创建聊天室 */
    public boolean createChatRoom(String roomId) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        io.rong.methods.chatroom.Chatroom chatroom = rongCloud.chatroom;
        Reader reader = null;
        ChatroomModel[] chatrooms = {new ChatroomModel().setId(roomId).setName(roomId)};
        try {
            ResponseResult result = chatroom.create(chatrooms);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /*销毁聊天室*/
    public boolean destoryChatRoom(String roomId) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        io.rong.methods.chatroom.Chatroom chatroom = rongCloud.chatroom;
        ChatroomModel chatroomModel = new ChatroomModel().setId(roomId);
        try {
            ResponseResult result = chatroom.destroy(chatroomModel);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /*禁言聊天室*/
    public boolean tabooChatRoom(String roomId, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Ban ban = rongCloud.chatroom.ban;
        ChatroomMember[] members = new ChatroomMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new ChatroomMember().setId(userIds[i]);
        }
        ChatroomModel chatroom = new ChatroomModel();
        chatroom.setId(roomId).setMembers(members).setMinute(600);
        try {
            ResponseResult result = ban.add(chatroom);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /*解除禁言聊天室*/
    public boolean closeTabooChatRoom(String roomId, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Ban ban = rongCloud.chatroom.ban;
        ChatroomMember[] members = new ChatroomMember[userIds.length];
        for (int i = 0; i < userIds.length; i++) {
            members[i] = new ChatroomMember().setId(userIds[i]);
        }
        ChatroomModel chatroom = new ChatroomModel();
        chatroom.setId(roomId).setMembers(members);
        try {
            ResponseResult result = ban.remove(chatroom);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    /*白名单设置*/
    public boolean tabooWhiteChatRoom(String roomId, String[] userIds) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        BanAllMemberWhitelist banAllMemberWhitelist = rongCloud.chatroom.banAllMemberWhitelist;
        ChatroomMember[] members = new ChatroomMember[userIds.length];
        for (int i = 0; i < members.length; i++) {
            ChatroomMember member = new ChatroomMember().setId(userIds[i]);
            members[i] = member;
        }
        ChatroomModel chatroom = new ChatroomModel().setMembers(members).setId(roomId);
        try {
            ResponseResult result = banAllMemberWhitelist.add(chatroom);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 融云封禁
     * <p>
     * 如果被封禁用户此时已经与融云保持连接，封禁后会即时断开将该用户的 IM 连接。
     * 被封禁用户无法与融云建立 IM 连接服务，无法主动使用 IM 服务。
     * 被封禁期间，其他用户可向被封禁用户发送消息，但被封禁用户无法接收消息，
     * 无法收到推送通知。解封后用户可正常连接融云使用 IM 服务，再次上线可以收到被封禁期间的离线消息?。
     * 请注意，离线消息最长存储 7 天，如果 7 天内客户端都没有上线，服务端将抛弃掉过期的消息。
     *
     * @param userId
     * @param minute 封禁时长，单位为分钟，最大值为 43200 分钟。
     * @return
     */
    @Override
    public boolean ban(String userId, Integer minute) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        Block block = rongCloud.user.block;
        UserModel user = new UserModel().setId(userId).setMinute(minute);
        try {
            Result result = block.add(user);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 设置用户单聊禁言
     *
     * @param userId 被禁言用户 ID，支持批量设置，最多不超过 1000 个
     * @param state  禁言状态，0 解除禁言、1 添加禁言
     * @return
     */
    @Override
    public boolean prohibition(String[] userId, Integer state) {
        RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
        io.rong.methods.user.chat.Ban ban = rongCloud.user.ban;
        //type  -- 会话类型，目前支持单聊会话 PERSON
        BanModel model = new BanModel().setUserId(userId).setState(state).setType("PERSON");
        try {
            Result result = ban.set(model);
            if (result.code == 200) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 注销用户
     *
     * @param userId
     * @return
     */
    @Override
    public boolean deactivate(String userId) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("&userId=").append(URLEncoder.encode(userId, "UTF-8"));
            String body = sb.toString();
            if (body.indexOf("&") == 0) {
                body = body.substring(1);
            }
            RongCloud rongCloud = RongCloud.getInstance(rongYunKey, rongYunSecret);
            HttpURLConnection conn = HttpUtil.CreatePostHttpConnection(rongCloud.getConfig(), rongYunKey, rongYunSecret, "/user/deactivate.json", "application/x-www-form-urlencoded");
            HttpUtil.setBodyParameter(body, conn, rongCloud.getConfig());
            String result = HttpUtil.returnResult(conn, rongCloud.getConfig());
            JSONObject json = JSONObject.parseObject(result);
            return Objects.equals("200", json.getString("code"));
        } catch (Exception e) {
            Log.error(e.toString());
            return false;
        }
    }

}
